# coding: utf-8
from typing import List

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QVBoxLayout
from qfluentwidgets import BodyLabel, setFont
from loguru import logger

from ...components import VerticalScrollArea, GridLayout, ComicCard, queue_thread_manager, Alert
from ...common import signalBus, BookItemModel
from ...common.db_model import TableBookShelf, is_book_shelf_exist, add_book_shelf, delete_book_shelf, \
    read_all_book_shelf


class BookShelfInterface(VerticalScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWidget()
        self.verticalLayout = QVBoxLayout(self.view)
        self.titleLabel = BodyLabel("书架", self.view)
        self.gridLayout = GridLayout()

        self.__initWidgets()
        self.loadBookShelf()

    def __initWidgets(self):
        self.setWidget(self.view)
        self.setObjectName("BookShelfInterface")

        setFont(self.titleLabel, 20)
        self.gridLayout.setItemMinimumWidth(150)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.titleLabel)
        self.verticalLayout.addLayout(self.gridLayout)

        signalBus.addBookSignal.connect(self.onAddBook)
        signalBus.removeBookSignal.connect(self.removeBook)

    def onAddBook(self, book: BookItemModel):
        logger.debug(f'添加书籍：{book.title}')
        queue_thread_manager.sqlRequest(add_book_shelf, book, slot=self.onAddBookCallback)

    def addBook(self, book: BookItemModel):
        card = ComicCard(self.view)
        card.setModel(book)
        logger.debug(f'添加书籍卡片：{book.title}')
        self.gridLayout.addWidget(card)

    def removeBook(self, book: BookItemModel):
        queue_thread_manager.sqlRequest(delete_book_shelf, book.info_url)

    def loadBookShelf(self):
        queue_thread_manager.sqlRequest(read_all_book_shelf, slot=self.onLoadBookShelfCallback)

    def onLoadBookShelfCallback(self, books: List[BookItemModel]):
        self.gridLayout.takeAllWidgets()
        for book in books:
            self.addBook(book)

    def onAddBookCallback(self):
        Alert.success(f'添加书籍成功')
        self.loadBookShelf()
